import { MciNotification } from '@/components/base';
// import * as i18n from '@/locales';
import { useAppStore } from '@/store/app';
import { get, post } from '@/utils/fetch';
interface IGetPolicyConfigParams {
  callbackHost?: string;
  callbackPath?: string;
  filename: string;
}

export interface IPolicyConfig {
  accessid: string;
  bucket: string;
  callback: string;
  dir: string;
  endpoint: string;
  expireAt: number;
  filePath: string;
  filename: string;
  host: string;
  pathKey: string;
  policy: string;
  signature: string;
}

/** 网关类型 */
export type TGateway = 'op' | 'project' | 'toolbox' | 'trade' | 'portfolio' | 'contract' | 'pay';

const checkGateway = (gateway: TGateway) => {
  if (!gateway) {
    throw new Error('Fail, The gateway is empty');
  }
};

/**
 * 获取oss上传密钥签名
 * @param gateway 网关名
 */
export const getPolicyConfig = (gateway: TGateway, body: IGetPolicyConfigParams) => {
  checkGateway(gateway);
  return get<IPolicyConfig>(`/${gateway}/oss/default/policy`, {
    headers: { Authorization: `Bearer ${useAppStore().keycloak.token}` },
    body
  });
};

/**
 * 获取指定文件的带签名访问路径
 * @param gateway 网关名
 * @param filePath 文件路径
 * @returns 签名后的路径
 */
export const getBucketAccessUrl = (gateway: TGateway, filePath?: string, isAll = false) => {
  checkGateway(gateway);
  if (!filePath) return Promise.resolve('');
  if (filePath.includes('#')) {
    // MciNotification.error(i18n.t('文件名不能包含') + '#');
    MciNotification.error('文件名不能包含' + '#');
    return Promise.reject('');
  }

  if (filePath.includes('+')) {
    // MciNotification.error(i18n.t('文件名不能包含') + '#');
    MciNotification.error('文件名不能包含' + '#');
    return Promise.reject('');
  }
  return post<string>(`/${gateway}/oss/bucket/access/url/v2`, {
    body: { filePath },
    isAll
  });
};
